//
//  XJLRViewController.m
//  运营管理系统
//
//  Created by 杨毅 on 16/9/28.
//  Copyright © 2016年 杨毅. All rights reserved.
//

#import "XJLRViewController.h"
static NSString *collectionViewCellId = @"collectionViewCellId";
static CGFloat imageSize = 80;

@interface XJLRViewController ()
{
    
    UIView *_backView3;
    UIView *_backView4;
    UIView *_backView5;
    UIView *_backView6;
    UIView *_backView7;
    
    UIView *_backView8;
    UIView *_backView9;
    UIView *_backView10;
    UIView *_backView11;
    ZJSwitch *_partSwit;//是否更换配件
    ZJSwitch *_swi;//是否异常
    UIButton *_btn;//故障上报详情
    NSArray *_content_arr;
    NSArray *_data;//传给view
    NSMutableArray *_GZtype;
    

    NSString *_btnTitle;
    PHATextView *_bztextView;
    NSInteger equipState;
    NSInteger state;//上报状态
    NSInteger stat;//搜索单号是否成功 1成功
    NSMutableArray *_typeID;
    NSInteger faultType;//故障类型id
    NSInteger sbid;//设备id
    NSString *_time;
    NSInteger k;
    UITextField *_Number;//出库单号
    NSMutableArray *_mtpcsArry;//存储存在书库单的数据
    

    NSInteger closeState;//删除按键点击状态
    NSMutableArray *_alldata;//tableview 数据来源
    NSMutableArray *_listarr;//上传参数 partList
    NSDictionary *_paramete;//参数
    UIButton *_startTime;
    UIButton *_endTime;
    NSInteger btnTag;
    
    BOOL isSelect;
    ChooseMenus *_MenusView;
    
    NSString *_place;
    CGFloat lnt;
    CGFloat lat;
    CLLocationManager *_LocationManager; //定位管理器
    
    UIButton *_updata;//提交按键
    UIView *_AddressView;
    UILabel *_addressL;
    
    NSMutableArray *_UpPsonNameArr;//上级人员
    
    NSInteger UpPsonid;
}

@property(nonatomic,strong)AFHTTPSessionManager *manager;
@property(nonatomic,strong)UIScrollView *scrollView;
@property(nonatomic, strong) UICollectionView *collectionView; //添加图片,每个cell内有一个imageView
@property(nonatomic, strong) NSMutableArray *imageArray;
@property(nonatomic, strong)UITableView *tableview;
@property(nonatomic, strong)PopupView *Popview;
@property (nonatomic,strong)NSMutableArray *dataSource0;
@property (nonatomic,strong)NSMutableArray *dataSource1;
@property (nonatomic,strong)NSMutableArray *dataSource2;
@property (nonatomic,strong)NSMutableArray *typeIDArr1;
@property (nonatomic,strong)NSMutableArray *typeIDArr2;
@property (nonatomic,strong)NSMutableArray *typeIDArr3;
@property (nonatomic,strong)NSMutableArray *UpPsonId;

@property (nonatomic,strong)UIButton *refreshBtn;
@end

@implementation XJLRViewController

- (AFHTTPSessionManager *)manager{

    if (!_manager) {
        _manager = [AFHTTPSessionManager manager];
    }
    return _manager;
}
- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:YES];
    self.automaticallyAdjustsScrollViewInsets = NO;
    [self SBnetworking];
    [self dingwei];
    [self shangjiPsonLoad];
}
- (void)shangjiPsonLoad{
    
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:K_UpPsonURL parameters:@{@"userId":[NSString stringWithFormat:@"%ld",self.userId]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [_UpPsonId removeAllObjects];
        [_UpPsonNameArr removeAllObjects];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        YYUpPsonDataModel *datamodel = [[YYUpPsonDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (YYUpPsonBeanList *model in datamodel.beanList) {
            NSString *str = [NSString stringWithFormat:@"%@%c%@%c",model.userN,'(',model.postName,')'];
            [_UpPsonNameArr addObject:str];
            [_UpPsonId addObject:[NSString stringWithFormat:@"%ld",model.userId]];
        }
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.title = @"巡检录入";
    self.view.backgroundColor = [UIColor whiteColor];
    UIBarButtonItem *leftItem = [[UIBarButtonItem alloc]initWithImage:[[UIImage imageNamed:@"back"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    self.navigationItem.leftBarButtonItem = leftItem;
    _UpPsonNameArr = [[NSMutableArray alloc]init];
    _UpPsonId = [[NSMutableArray alloc]init];
    self.scrollView = [[UIScrollView alloc]init];
    self.scrollView.frame = CGRectMake(0, 64, kSCREEN_WIDTH, kSCREEN_HEIGHT-64);
    self.scrollView.backgroundColor = UIColorFromRGB(0xf0f0f0);
    //self.scrollView.contentSize = CGSizeMake(kSCREEN_WIDTH, kSCREEN_HEIGHT*2+100);
    [self.view addSubview:self.scrollView];
    // 隐藏水平滚动条
    self.scrollView.showsHorizontalScrollIndicator = NO;
    self.scrollView.showsVerticalScrollIndicator = NO;
    _AddressView = [[UIView alloc]initWithFrame:CGRectMake(0, 5, kSCREEN_WIDTH, 40)];
    _AddressView.backgroundColor = UIColorFromRGB(0xf7f3be);
    [self.scrollView addSubview:_AddressView];
    UIImageView *location = [[UIImageView alloc]initWithFrame:CGRectMake(5, 6, 21, 28)];
    location.image = [UIImage imageNamed:@"position"];
    [_AddressView addSubview:location];
    _addressL = [[UILabel alloc]initWithFrame:CGRectMake(26, 0, kSCREEN_WIDTH-106, 40)];
    _addressL.textColor = UIColorFromRGB(0x4d4d4d);
    _addressL.font = [UIFont systemFontOfSize:15.0];
    _addressL.numberOfLines = 2;
    [_AddressView addSubview:_addressL];
    self.refreshBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.refreshBtn setTitle:@"重新定位" forState:UIControlStateNormal];
    [self.refreshBtn setTitleColor:UIColorFromRGB(0x0093d5) forState:UIControlStateNormal];
    self.refreshBtn.titleLabel.font = [UIFont systemFontOfSize:15.0];
    [self.refreshBtn addTarget:self action:@selector(refreshLocation:) forControlEvents:UIControlEventTouchUpInside];
    [_AddressView addSubview:self.refreshBtn];



    self.imageArray = [NSMutableArray array];

    UIApplication *app =[UIApplication sharedApplication];
    AppDelegate *delegate = app.delegate;
    self.username = delegate.username;
    self.userId = delegate.userId;
    isSelect = NO;
    [self load];
    

    
    //获取通知中心单例对象
    NSNotificationCenter * center = [NSNotificationCenter defaultCenter];
    //添加当前类对象为一个观察者，name和object设置为nil，表示接收一切通知
    [center addObserver:self selector:@selector(notice:) name:@"cellnotice1" object:nil];
    //初始状态
    stat = 2;//没有滑动跟换配件开关  上传没有参数partList partNum
    equipState = 1;//异常状态 1正常 2异常
    state = 0;//上报状态  默认0不上报
    faultType = 0;//选了上报 但没有填写故障上报详情
    sbid = 0;//选择上报 但没有填写故障上报详情
    
    _dataSource0 = [[NSMutableArray alloc]init];
    _dataSource1 = [[NSMutableArray alloc]init];
    _dataSource2 = [[NSMutableArray alloc]init];
    _typeIDArr1  = [[NSMutableArray alloc]init];
    _typeIDArr2  = [[NSMutableArray alloc]init];
    _typeIDArr3  = [[NSMutableArray alloc]init];
    _SBArry = [[NSMutableArray alloc]init];
    _eqidArray = [[NSMutableArray alloc]init];
    
}
- (void)dingwei{
    //实例化定位管理器
    _LocationManager = [[CLLocationManager alloc] init];
    
    _LocationManager.delegate = self;
    
    //请求用户同意定位
    //只在前台定位
    //在项目的配置文件Info.plist中添加以下内容
    //NSLocationWhenInUseUsageDescription
    if ([[[UIDevice currentDevice] systemVersion] doubleValue] > 8.0) {
        [_LocationManager requestAlwaysAuthorization];
    }
    
    //允许在后台定位
    //NSLocationAlwaysUsageDescription
    //[_manager requestAlwaysAuthorization];
    
    //设置定位的精度和更新频率
    /*
     kCLLocationAccuracyBestForNavigation  导航
     kCLLocationAccuracyBest;              较好的精度
     kCLLocationAccuracyNearestTenMeters;  10米
     kCLLocationAccuracyHundredMeters;     100米
     kCLLocationAccuracyKilometer;         1000米
     kCLLocationAccuracyThreeKilometers;   3000米
     */
    _LocationManager.desiredAccuracy = kCLLocationAccuracyBest; //定位的精度
    
    _LocationManager.distanceFilter = 100; //更新频率
    if ([CLLocationManager locationServicesEnabled]) { // 判断是否打开了位置服务
        //启动定位
        [_LocationManager startUpdatingLocation]; // 开始更新位置
    }else{
        
    }
}
- (void)locationManager:(CLLocationManager *)manager didChangeAuthorizationStatus:(CLAuthorizationStatus)status
{
    switch (status) {
        case kCLAuthorizationStatusNotDetermined:
            if ([_LocationManager respondsToSelector:@selector(requestAlwaysAuthorization)]) {
                
                [_LocationManager requestWhenInUseAuthorization];     //NSLocationWhenInUseDescription
                [_LocationManager requestAlwaysAuthorization];
            }
            break;
        default:
            break;
            
            
    }
}
/** 不能获取位置信息时调用*/
-(void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error
{
    NSLog(@"%@",error);
    
//    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"温馨提示" message:@"定位失败请重新提交" preferredStyle:UIAlertControllerStyleAlert];
//    UIAlertAction *cancelAction  = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//        
//    }];
//    
//    UIAlertAction *OKAction  = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//        NSLog(@"点击了知道了");
//        
//    }];
//    [alertVC addAction:cancelAction];
//    [alertVC addAction:OKAction];
//    [self presentViewController:alertVC animated:YES completion:nil];
}
//定位成功后会执行的函数
- (void)locationManager:(CLLocationManager *)manager
     didUpdateLocations:(NSArray *)locations
{
    
    CLLocation *currentLocation = [locations firstObject];
    NSLog(@"%@",currentLocation);
    
    // CLLocation *newLocation = [locations lastObject];
    CLLocationCoordinate2D oldCoordinate = currentLocation.coordinate;
    
    NSLog(@"旧的经度：%f,旧的纬度：%f",oldCoordinate.longitude,oldCoordinate.latitude);
    lat = oldCoordinate.latitude;
    lnt = oldCoordinate.longitude;
    //获取当前所在的城市名
    CLGeocoder *geocoder = [[CLGeocoder alloc] init];
    //根据经纬度反向地理编译出地址信息
    [geocoder reverseGeocodeLocation:currentLocation completionHandler:^(NSArray *array, NSError *error)
     {
         if (array.count > 0)
         {
             CLPlacemark *placemark = [array firstObject];
             
             //NSSLog(@"%@",placemark.administrativeArea);//省份
             //获取城市
             NSString *city = placemark.locality;
             if (!city) {
                 //四大直辖市的城市信息无法通过locality获得，只能通过获取省份的方法来获得（如果city为空，则可知为直辖市）
                 city = placemark.administrativeArea;
             }
             //NSString  *cityName = city;
             
             //系统会一直更新数据，直到选择停止更新，因为我们只需要获得一次经纬度即可，所以获取之后就停止更新
             NSMutableString *str = [[NSMutableString alloc]init];
             [str appendString:placemark.administrativeArea];
             if (placemark.locality.length>0){
                 [str appendString:placemark.locality];
             }
             if (placemark.subLocality.length>0) {
                 [str appendString:placemark.subLocality];
             }
             if (placemark.thoroughfare.length>0) {
                 [str appendString:placemark.thoroughfare];
             }
             if (placemark.subThoroughfare.length>0) {
                 [str appendString:placemark.subThoroughfare];
             }
             //_place = str;//城市地区街道子街道
             _place = [NSString stringWithFormat:@"%@",str];
             
             _addressL.text = _place;
             if (_addressL.text.length < 1) {
                 self.refreshBtn.frame = CGRectMake(26, 0,kSCREEN_WIDTH-52, 40);
                 
             }else{
                 self.refreshBtn.frame = CGRectMake(CGRectGetMaxX(_addressL.frame), 0,80, 40);
             }

         }else if (error == nil && [array count] == 0)
         {
             NSLog(@"No results were returned.");
         }else if (error != nil)
         {
             NSLog(@"An error occurred = %@", error);
         }
     }];
    [manager stopUpdatingLocation];

}

- (void)load{
    
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    hud.labelText = @"加载中...";

    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:K_XJBmassage parameters:@{stationID:[NSString stringWithFormat:@"%ld",self.stationid]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSDictionary *Fau = dic[@"data"][@"FaultRecd"];
         NSInteger sta = [Fau[@"state"]integerValue];
        _content_arr = @[Fau[@"stationName"],Fau[@"pson"],Fau[@"time"],[NSString stringWithFormat:@"%ld",sta]];
        NSDate *currentDate = [NSDate date];//获取当前时间，日期
        NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
        [dateFormatter setDateFormat:@"YYYY-MM-dd hh:mm:ss"];
        _time = [dateFormatter stringFromDate:currentDate];
        _data = @[@"",Fau[@"pson"],_time];
        [self initScorlleview];
    [MBProgressHUD hideHUDForView:self.view animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}
- (void)initScorlleview{
    
    //故障基本信息背景
    UIView *backView1 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_AddressView.frame)+5, kSCREEN_WIDTH, 50)];
    backView1.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backView1];

    //故障基本信息图标 d_icon01   编辑图标d_icon04 大小30*30
    UIImageView *gzMimageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 30, 30)];
    gzMimageView.image = [[UIImage imageNamed:@"d_icon01"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [backView1 addSubview:gzMimageView];
    
    UILabel *title = [[UILabel alloc]initWithFrame:CGRectMake(45, 15, 180, 21)];
    title.text = @"录入站点基本信息";
    title.adjustsFontSizeToFitWidth = YES;
    title.font = [UIFont systemFontOfSize:21.0];
    title.textColor = UIColorFromRGB(0x0093d5);
    [backView1 addSubview:title];
    
    //基本信息详情背景
    UIView *backView2 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(backView1.frame)+2, kSCREEN_WIDTH, 140)];
    backView2.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:backView2];

    
    
    NSArray *leftTitle_arr = @[@"所属站点",@"负责人员",@"上次巡检时间",@"上次巡检状态"];
    
    
    for (NSInteger i = 0; i < leftTitle_arr.count; ++i) {
        
        if (i<2) {
            
            UILabel *titleName = [[UILabel alloc]initWithFrame:CGRectMake(10, 10 + i * (21+10), 80, 21)];
            titleName.adjustsFontSizeToFitWidth = YES;
            titleName.font = [UIFont systemFontOfSize:15.0];
            titleName.textColor = UIColorFromRGB(0x4d4d4d);
            titleName.text = leftTitle_arr[i];
            [backView2 addSubview:titleName];
            UILabel *content = [[UILabel alloc]initWithFrame:CGRectMake(110, 5 + i * (30+1), kSCREEN_WIDTH-110, 30)];
            content.adjustsFontSizeToFitWidth = YES;
            content.text = _content_arr[i];
            content.backgroundColor = UIColorFromRGB(0xf0f0f0);
            content.font = [UIFont systemFontOfSize:13.0];
            content.textColor = UIColorFromRGB(0x4d4d4d);
            [backView2 addSubview:content];
        }else{
        
            UILabel *titleName = [[UILabel alloc]initWithFrame:CGRectMake(10, 10 + i * (21+10), 110, 21)];
            titleName.adjustsFontSizeToFitWidth = YES;
            titleName.font = [UIFont systemFontOfSize:15.0];
            titleName.textColor = UIColorFromRGB(0x4d4d4d);
            titleName.text = leftTitle_arr[i];
            [backView2 addSubview:titleName];
            if (i==2) {
                UILabel *content = [[UILabel alloc]initWithFrame:CGRectMake(110, 5 + i * (30+1), kSCREEN_WIDTH-110, 30)];
                content.adjustsFontSizeToFitWidth = YES;
                content.text = _content_arr[i];
                content.backgroundColor = UIColorFromRGB(0xf0f0f0);
                content.font = [UIFont systemFontOfSize:13.0];
                content.textColor = UIColorFromRGB(0x4d4d4d);
                [backView2 addSubview:content];
                
            }else{
                //巡检状态
                UIView *stBackView = [[UIView alloc]initWithFrame:CGRectMake(110, 5 + i * (30+1), kSCREEN_WIDTH-110, 30)];
                stBackView.backgroundColor = UIColorFromRGB(0xf0f0f0);
                [backView2 addSubview:stBackView];
                //状态图片gif
                UIImageView *stateView = [[UIImageView alloc]init];
                
                [stBackView addSubview:stateView];
                [stateView mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(stBackView).offset(5);
                    make.top.equalTo(stBackView).offset(2.5);
                    make.size.mas_equalTo(CGSizeMake(25, 25));
                }];
                UILabel *stataLab = [[UILabel alloc]init];
                stataLab.adjustsFontSizeToFitWidth = YES;
                stataLab.font = [UIFont systemFontOfSize:13.0];
                stataLab.textColor = UIColorFromRGB(0x4d4d4d);
                [stBackView addSubview:stataLab];
                [stataLab mas_makeConstraints:^(MASConstraintMaker *make) {
                    make.left.equalTo(stateView.mas_right).offset(10);
                    make.top.equalTo(stBackView).offset(0);
                    make.size.mas_equalTo(CGSizeMake(80, 30));
                }];
                
                if ([_content_arr[i]integerValue] == 2) {

                    UIImage *image = [UIImage sd_animatedGIFNamed:@"off_line"];
                    stateView.image = image;
                    stataLab.text = @"异常";
                }else if([_content_arr[i]integerValue] == 1){
                    
                    UIImage *image = [UIImage sd_animatedGIFNamed:@"on_line"];
                    stateView.image = image;
                    stataLab.text = @"正常";
                }else{
                
                    NSLog(@"不显示");
                }

            }
        }

    }
    //巡检录入
    _backView3 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(backView2.frame)+10, kSCREEN_WIDTH, 250)];
    _backView3.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_backView3];

    UIImageView *editImageView = [[UIImageView alloc]initWithFrame:CGRectMake(10, 10, 30, 30)];
    editImageView.image = [[UIImage imageNamed:@"d_icon04"]imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal];
    [_backView3 addSubview:editImageView];
    UILabel *title2 = [[UILabel alloc]initWithFrame:CGRectMake(45, 15, 150, 21)];
    title2.adjustsFontSizeToFitWidth = YES;
    title2.text = @"巡检录入";
    title2.font = [UIFont systemFontOfSize:21.0];
    title2.textColor = UIColorFromRGB(0x0093d5);
    [_backView3 addSubview:title2];
    


    NSArray *leftT = @[@"录入人",@"开始时间",@"结束时间",@"是否异常",@"配件跟换"];
    
    for (NSInteger i = 0; i < leftT.count; ++i) {
        UIView *line = [[UIView alloc]initWithFrame:CGRectMake(0, 46 + i * (1 + 40), kSCREEN_WIDTH, 1)];
        line.backgroundColor = UIColorFromRGB(0xf0f0f0);
        [_backView3 addSubview:line];
        UILabel *leftTitle = [[UILabel alloc]initWithFrame:CGRectMake(0, 56 + i * (21 + 20), kSCREEN_WIDTH/4+20, 21)];
        leftTitle.adjustsFontSizeToFitWidth = YES;
        leftTitle.text = leftT[i];
        leftTitle.font = [UIFont systemFontOfSize:15.0];
        leftTitle.textColor = UIColorFromRGB(0x4d4d4d);
        leftTitle.textAlignment = NSTextAlignmentRight;
        [_backView3 addSubview:leftTitle];
        
        if (i == 3) {
            _partSwit = [[ZJSwitch alloc]initWithFrame:CGRectMake(kSCREEN_WIDTH/4+20, 60 + i * (30 + 8), 60, 30)];
            _partSwit.tintColor = [UIColor lightGrayColor];
            _partSwit.transform = CGAffineTransformMakeScale(0.75, 0.75);
            _partSwit.onText = @"是";
            _partSwit.offText = @"否";

            [_partSwit addTarget:self action:@selector(handleSwitch1:) forControlEvents:UIControlEventValueChanged];
            [_backView3 addSubview:_partSwit];
            _btn = [UIButton buttonWithType:UIButtonTypeSystem];
            _btn.frame = CGRectMake(CGRectGetMaxX(_partSwit.frame)+20, 60 + i * (30 + 8), 120, 30);
            [_btn setTitle:@"填写故障信息" forState:UIControlStateNormal];
            _btn.titleLabel.font = [UIFont systemFontOfSize:15.0];
            [_btn setTitleColor:UIColorFromRGB(0x0093d5) forState:UIControlStateNormal];
            //button 标题对齐方式
            _btn.contentHorizontalAlignment = UIControlContentHorizontalAlignmentCenter;
            //一开始不显示
            _btn.alpha = 0;
            [_btn addTarget:self action:@selector(initPopView) forControlEvents:UIControlEventTouchUpInside];
            [_backView3 addSubview:_btn];

        }else if (i == 1){
            _startTime = [UIButton buttonWithType:UIButtonTypeCustom];
            [_startTime setTitle:@"选择时间" forState:UIControlStateNormal];
            [_startTime setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
            _startTime.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            _startTime.backgroundColor = UIColorFromRGB(0xf0f0f0);
            _startTime.frame = CGRectMake(kSCREEN_WIDTH/4+30, 60 + i * (21 + 15), kSCREEN_WIDTH/3*2-20, 21);
            _startTime.titleLabel.font = [UIFont systemFontOfSize:15.0];
            _startTime.tag = 2001;
            [_startTime addTarget:self action:@selector(chooseTime:) forControlEvents:UIControlEventTouchUpInside];
            [_backView3 addSubview:_startTime];
        }else if (i == 2){
            _endTime = [UIButton buttonWithType:UIButtonTypeCustom];
            [_endTime setTitle:@"选择时间" forState:UIControlStateNormal];
            [_endTime setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
            _endTime.contentHorizontalAlignment = UIControlContentHorizontalAlignmentLeft;
            _endTime.backgroundColor = UIColorFromRGB(0xf0f0f0);
            _endTime.frame = CGRectMake(kSCREEN_WIDTH/4+30, 56 + i * (21 + 20), kSCREEN_WIDTH/3*2-20, 21);
            _endTime.titleLabel.font = [UIFont systemFontOfSize:15.0];
            _endTime.tag = 2002;
            [_endTime addTarget:self action:@selector(chooseTime:) forControlEvents:UIControlEventTouchUpInside];
            
            [_backView3 addSubview:_endTime];
        }else if (i == 4){
            _swi = [[ZJSwitch alloc]initWithFrame:CGRectMake(kSCREEN_WIDTH/4+20, 64 + i * (30 + 8), 60, 30)];
            _swi.transform = CGAffineTransformMakeScale(0.75, 0.75);
            _swi.tintColor = [UIColor lightGrayColor];
            _swi.onText = @"是";
            _swi.offText = @"否";
            // _swi.tag = 1001;
            [_swi addTarget:self action:@selector(handleSwitch2:) forControlEvents:UIControlEventValueChanged];
            [_backView3 addSubview:_swi];
        }else{
            UILabel *rightCount = [[UILabel alloc]initWithFrame:CGRectMake(kSCREEN_WIDTH/4+30, 56 + i * (21 + 20), kSCREEN_WIDTH/3*2, 21)];
            rightCount.adjustsFontSizeToFitWidth = YES;
            rightCount.text = self.username;
            rightCount.textColor = UIColorFromRGB(0x4d4d4d);
            rightCount.font = [UIFont systemFontOfSize:13.0];
            [_backView3 addSubview:rightCount];
        }
    }
    //竖线
    UIView *line2 = [[UIView alloc]initWithFrame:CGRectMake(kSCREEN_WIDTH/4+20, 46, 1, 204)];
    line2.backgroundColor = UIColorFromRGB(0xf0f0f0);
    [_backView3 addSubview:line2];
    
    _backView5 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView3.frame)+2, kSCREEN_WIDTH, 200)];
    _backView5.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_backView5];
    //图片上传
    UILabel *photoUp = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 60, 21)];
    photoUp.adjustsFontSizeToFitWidth = YES;
    photoUp.text = @"图片上传";
    photoUp.textColor = UIColorFromRGB(0x4d4d4d);
    photoUp.font = [UIFont systemFontOfSize:15.0];
    [_backView5 addSubview:photoUp];

    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    layout.itemSize = CGSizeMake(imageSize, imageSize);
    layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
    
    layout.minimumLineSpacing = 10;
    UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(80, 0, self.view.frame.size.width-90, imageSize + 20) collectionViewLayout:layout];
    self.collectionView = collectionView;
    [self.collectionView registerClass:[KKUploadPhotoCollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellId];
    self.collectionView.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
    self.collectionView.delegate = self;
    self.collectionView.dataSource = self;
    self.collectionView.backgroundColor = [UIColor whiteColor];
    [_backView5 addSubview:collectionView];
    //备注信息
    UILabel *BZmassage = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(collectionView.frame)+5, 80, 21)];
    BZmassage.adjustsFontSizeToFitWidth = YES;
    BZmassage.text = @"备注信息";
    BZmassage.textColor = UIColorFromRGB(0x4d4d4d);
    BZmassage.font = [UIFont systemFontOfSize:15.0];
    [_backView5 addSubview:BZmassage];

    
    _bztextView = [[PHATextView alloc]initWithFrame:CGRectMake(90, CGRectGetMaxY(collectionView.frame)+5, kSCREEN_WIDTH/4*3-10, 80)];
    _bztextView.font = [UIFont systemFontOfSize:15.0];
    _bztextView.backgroundColor = UIColorFromRGB(0xf0f0f0);
    _bztextView.placeholder = @"不超过100个字符";
    _bztextView.returnKeyType = UIReturnKeyDone;
    _bztextView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
    _bztextView.layer.borderWidth = 0.5;
    _bztextView.layer.cornerRadius = 3;
    [_backView5 addSubview:_bztextView];

    _backView6 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView5.frame)+10, kSCREEN_WIDTH, 60)];
    _backView6.backgroundColor = [UIColor whiteColor];
    [self.scrollView addSubview:_backView6];

    //提交取消bttuon
    _updata = [UIButton buttonWithType:UIButtonTypeSystem];
    [_updata setTitle:@"提交" forState:UIControlStateNormal];
    [_updata setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    _updata.backgroundColor = UIColorFromRGB(0x2dd500);
    [_updata addTarget:self action:@selector(up) forControlEvents:UIControlEventTouchUpInside];
    [_backView6 addSubview:_updata];
    [_updata mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_backView6).offset(10);
        make.left.equalTo(self.scrollView).offset((kSCREEN_WIDTH/3-20)/2);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
    }];
    
    UIButton *cancerl = [UIButton buttonWithType:UIButtonTypeSystem];
    [cancerl setTitle:@"取消" forState:UIControlStateNormal];
    [cancerl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [cancerl addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
    cancerl.backgroundColor = UIColorFromRGB(0xd50037);
    [_backView6 addSubview:cancerl];
    [cancerl mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_backView6).offset(10);
        make.left.equalTo(_updata.mas_right).offset(20);
        make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
    }];
    self.scrollView.contentSize = CGSizeMake(kSCREEN_WIDTH, CGRectGetMaxY(_backView6.frame)+50);

}
#pragma mark  UICollectionView数据源方法
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    if (self.imageArray.count < 5) {
        return self.imageArray.count + 1;
    }
    return self.imageArray.count;
}
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    KKUploadPhotoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:collectionViewCellId forIndexPath:indexPath];
    //添加子控件,设置布局与控件图片
    [self addAndSetSubViews:cell indexPath:indexPath];
    return cell;
}

- (void)addAndSetSubViews:(KKUploadPhotoCollectionViewCell *)cell indexPath:(NSIndexPath *)indexPath{
    //清空子控件,解决重用问题
    NSArray *subviews = [[NSArray alloc] initWithArray:cell.contentView.subviews];
    for (UIView *subview in subviews) {
        [subview removeFromSuperview];
    }
    UIImageView *imageView = [[UIImageView alloc]init];
    [cell.contentView addSubview:imageView];
    imageView.contentMode = UIViewContentModeScaleAspectFill;
    imageView.layer.masksToBounds = YES;
    cell.tag = 11; //根据tag值设定是否可点击,11可点击,初始全部可点击
    cell.imageView = imageView;
    cell.backgroundColor = [UIColor whiteColor];
    if(indexPath.row == self.imageArray.count){
        imageView.image = [UIImage imageNamed:@"add"];
    }else{
        imageView.image = nil;
    }
    
    UIButton *cancleBtn = [[UIButton alloc]init];
    cell.cancleBtn = cancleBtn;
    [cell.contentView addSubview: cancleBtn];
    [cancleBtn setImage:[UIImage imageNamed:@"circle_delete"] forState:UIControlStateNormal];
    cancleBtn.hidden = YES;//初始将删除按钮隐藏
    cell.cancleBtn.tag = indexPath.row;
    [cell.cancleBtn addTarget:self action:@selector(cancleBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    
    cell.imageView.frame = CGRectMake(0, 0, imageSize, imageSize);
    cell.cancleBtn.frame = CGRectMake(60, 0, 20, 20);
    
    if (self.imageArray.count > indexPath.row) {
        if ([self.imageArray[indexPath.row] isKindOfClass:[UIImage class]]) {
            cell.imageView.image = nil;
            cell.imageView.image = self.imageArray[indexPath.row];
            cell.cancleBtn.hidden = NO;
            cell.tag = 10; //初始设置tag为11,当为10时,表示已经添加图片
        }
    }
    
}

#pragma mark  collectionView代理方法,添加照片
//点击collectionView跳转到相册
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    if ([collectionView cellForItemAtIndexPath:indexPath].tag == 11) {
        [[KKPhotoPickerManager shareInstace] showActionSheetInView:self.view fromController:self completionBlock:^(NSMutableArray *imageArray) {
            for (int i = 0; i<imageArray.count; i++) {
                if (self.imageArray.count < 5) {
                    UIImage *image = imageArray[i];
                    [self.imageArray addObject:image]; //上传图片保存到数组
                }
            }
            [self.collectionView reloadData];
        }];
    }
    
}

#pragma mark  删除图片
- (void)cancleBtnClick:(UIButton *)sender{
    if (sender.tag < self.imageArray.count) {
        [self.imageArray removeObjectAtIndex:sender.tag];
        sender.hidden = YES;
        [self.collectionView reloadData];
    }
}

//异常状态
- (void)handleSwitch1:(ZJSwitch *)sender{
    if (sender.isOn) {
        _btn.alpha = 1;
        equipState = 2;//异常状态
        state = 1;//上报状态  默认0不上报
    }else{
        _btn.alpha = 0;
        equipState = 1;//异常状态
        state = 0;//上报状态  默认0不上报
    }
}
//更换配件switch事件
- (void)handleSwitch2:(ZJSwitch *)sender{
    
    if (sender.isOn) {
        //stat = 2;
        [_backView5 removeFromSuperview];
        [_backView6 removeFromSuperview];
        _backView4 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView3.frame)+10, kSCREEN_WIDTH, 40)];
        _backView4.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_backView4];

        _Number = [[UITextField alloc]initWithFrame:CGRectMake(10, 5, kSCREEN_WIDTH-60, 30)];
        _Number.borderStyle = UITextBorderStyleNone;
        _Number.backgroundColor = UIColorFromRGB(0xf0f0f0);
        _Number.layer.cornerRadius = 5;
        _Number.placeholder = @"输入出库单号";
        [_backView4 addSubview:_Number];

        UIButton *searchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        searchBtn.frame = CGRectMake(CGRectGetMaxX(_Number.frame), 5, 40, 30);
        [searchBtn setTitle:@"搜索" forState:UIControlStateNormal];
        [searchBtn setTitleColor:UIColorFromRGB(0x0093d5) forState:UIControlStateNormal];
        [searchBtn addTarget:self action:@selector(searchClick) forControlEvents:UIControlEventTouchUpInside];
        [_backView4 addSubview:searchBtn];

        _backView5 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView4.frame)+10, kSCREEN_WIDTH, 200)];
        _backView5.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_backView5];

        //图片上传
        UILabel *photoUp = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 60, 21)];
        photoUp.adjustsFontSizeToFitWidth = YES;
        photoUp.text = @"图片上传";
        photoUp.textColor = UIColorFromRGB(0x4d4d4d);
        photoUp.font = [UIFont systemFontOfSize:15.0];
        [_backView5 addSubview:photoUp];

        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(imageSize, imageSize);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 10;
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(80, 0, self.view.frame.size.width-90, imageSize + 20) collectionViewLayout:layout];
        self.collectionView = collectionView;
        [self.collectionView registerClass:[KKUploadPhotoCollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellId];
        self.collectionView.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        self.collectionView.backgroundColor = [UIColor whiteColor];
        [_backView5 addSubview:collectionView];
        //备注信息
        UILabel *BZmassage = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(collectionView.frame)+5, 60, 21)];
        BZmassage.adjustsFontSizeToFitWidth = YES;
        BZmassage.text = @"备注信息";
        BZmassage.textColor = UIColorFromRGB(0x4d4d4d);
        BZmassage.font = [UIFont systemFontOfSize:15.0];
        [_backView5 addSubview:BZmassage];

        
        _bztextView = [[PHATextView alloc]initWithFrame:CGRectMake(90, CGRectGetMaxY(collectionView.frame)+5,kSCREEN_WIDTH/4*3-10, 80)];
        _bztextView.font = [UIFont systemFontOfSize:13.0];
        _bztextView.backgroundColor = UIColorFromRGB(0xf0f0f0);
        _bztextView.placeholder = @"不超过100个字符";
        _bztextView.returnKeyType = UIReturnKeyDone;
        //_bztextView.textColor = UIColorFromRGB(0x4d4d4d);
        _bztextView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        _bztextView.layer.borderWidth = 0.5;
        _bztextView.layer.cornerRadius = 3;
        [_backView5 addSubview:_bztextView];

        _backView6 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView5.frame)+10, kSCREEN_WIDTH, 60)];
        _backView6.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_backView6];
        
        //提交取消bttuon
        _updata = [UIButton buttonWithType:UIButtonTypeSystem];
        [_updata setTitle:@"提交" forState:UIControlStateNormal];
        [_updata setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _updata.backgroundColor = UIColorFromRGB(0x2dd500);
        [_updata addTarget:self action:@selector(up) forControlEvents:UIControlEventTouchUpInside];
        [_backView6 addSubview:_updata];
        [_updata mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_backView6).offset(10);
            make.left.equalTo(self.scrollView).offset((kSCREEN_WIDTH/3-20)/2);
            make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
        }];
        
        UIButton *cancerl = [UIButton buttonWithType:UIButtonTypeSystem];
        [cancerl setTitle:@"取消" forState:UIControlStateNormal];
        [cancerl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancerl addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        cancerl.backgroundColor = UIColorFromRGB(0xd50037);
        [_backView6 addSubview:cancerl];
        [cancerl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_backView6).offset(10);
            make.left.equalTo(_updata.mas_right).offset(20);
            make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
        }];
        self.scrollView.contentSize = CGSizeMake(kSCREEN_WIDTH, CGRectGetMaxY(_backView6.frame)+50);
    }else{
       
        //stat = 2;
        //移除搜索框 上传照片 提交 或者已经添加配件信息的视图  重新设置上传照片 提交取消 所在视图
        
         [_backView4 removeFromSuperview];
         [_backView5 removeFromSuperview];
         [_backView6 removeFromSuperview];
        _backView5 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView3.frame)+10, kSCREEN_WIDTH, 200)];
        _backView5.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_backView5];
        
        //图片上传
        UILabel *photoUp = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 60, 21)];
        photoUp.adjustsFontSizeToFitWidth = YES;
        photoUp.text = @"图片上传";
        photoUp.textColor = UIColorFromRGB(0x4d4d4d);
        photoUp.font = [UIFont systemFontOfSize:15.0];
        [_backView5 addSubview:photoUp];
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(imageSize, imageSize);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 10;
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(80, 0, self.view.frame.size.width-90, imageSize + 20) collectionViewLayout:layout];
        self.collectionView = collectionView;
        [self.collectionView registerClass:[KKUploadPhotoCollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellId];
        self.collectionView.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        self.collectionView.backgroundColor = [UIColor whiteColor];
        [_backView5 addSubview:collectionView];
        //备注信息
        UILabel *BZmassage = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(collectionView.frame)+5, 60, 21)];
        BZmassage.adjustsFontSizeToFitWidth = YES;
        BZmassage.text = @"备注信息";
        BZmassage.textColor = UIColorFromRGB(0x4d4d4d);
        BZmassage.font = [UIFont systemFontOfSize:15.0];
        [_backView5 addSubview:BZmassage];
        
        
        _bztextView = [[PHATextView alloc]initWithFrame:CGRectMake(90, CGRectGetMaxY(collectionView.frame)+5,kSCREEN_WIDTH/4*3-10, 80)];
        _bztextView.font = [UIFont systemFontOfSize:13.0];
        _bztextView.backgroundColor = UIColorFromRGB(0xf0f0f0);
        _bztextView.placeholder = @"不超过100个字符";
        _bztextView.returnKeyType = UIReturnKeyDone;
        //_bztextView.textColor = UIColorFromRGB(0x4d4d4d);
        _bztextView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        _bztextView.layer.borderWidth = 0.5;
        _bztextView.layer.cornerRadius = 3;
        [_backView5 addSubview:_bztextView];
        
        _backView6 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView5.frame)+10, kSCREEN_WIDTH, 60)];
        _backView6.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_backView6];
        
        //提交取消bttuon
        _updata = [UIButton buttonWithType:UIButtonTypeSystem];
        [_updata setTitle:@"提交" forState:UIControlStateNormal];
        [_updata setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _updata.backgroundColor = UIColorFromRGB(0x2dd500);
        [_updata addTarget:self action:@selector(up) forControlEvents:UIControlEventTouchUpInside];
        [_backView6 addSubview:_updata];
        [_updata mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_backView6).offset(10);
            make.left.equalTo(self.scrollView).offset((kSCREEN_WIDTH/3-20)/2);
            make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
        }];
        
        UIButton *cancerl = [UIButton buttonWithType:UIButtonTypeSystem];
        [cancerl setTitle:@"取消" forState:UIControlStateNormal];
        [cancerl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancerl addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        cancerl.backgroundColor = UIColorFromRGB(0xd50037);
        [_backView6 addSubview:cancerl];
        [cancerl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_backView6).offset(10);
            make.left.equalTo(_updata.mas_right).offset(20);
            make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
        }];
        self.scrollView.contentSize = CGSizeMake(kSCREEN_WIDTH, CGRectGetMaxY(_backView6.frame)+50);
    }
}

//搜索按键点击事件
- (void)searchClick{

    NSDictionary *paramet = @{MtPcsid:_Number.text};
    _mtpcsArry = [[NSMutableArray alloc]init];
    _alldata = [[NSMutableArray alloc]init];
    
    if (_Number.text.length == 0) {
        
        [self showAlert:@"输入单号" message:nil actionWithTitle:@"确定"];
        
    }else{
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:K_MtPcsBynum parameters:paramet progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        
        stat = [dic[@"status"]integerValue];
        if (stat == 1) {
            KdataModel *model = [[KdataModel alloc]initWithDictionary:dic[@"data"] error:nil];
            for (KmtPcsModel *MtModel in model.MtPcsDetail) {
                [_mtpcsArry addObject:MtModel];
            }
            for (NSInteger i = 0; i < _mtpcsArry.count; i++) {
                KmtPcsModel *model = _mtpcsArry[i];
                ExpenseModel *model1 = [[ExpenseModel alloc]init];
                model1.djnum = _Number.text;
                model1.PJnum = [NSString stringWithFormat:@"%ld",i+1];
                model1.aliph = @"0";
                model1.PJbianhao = model.logId;
                model1.value = model.numb;
                model1.discrib = model.discrib;
                model1.unit = model.unit;
                [_alldata addObject:model1];
            }
            //成功不允许开关滑动
            _swi.userInteractionEnabled = NO;
            //有单号删除搜索 图片上传 提交取消按键  重新设置图片上传 提交取消按键
            [self inittableview];
        }else if (stat == 2000){
            
            [self showAlert:@"温馨提示" message:@"该出库单号已被使用" actionWithTitle:@"确定"];
        
        }else{
            
            _swi.userInteractionEnabled = NO;
            stat = 2;
            PartChooseVC *vc = [[PartChooseVC alloc]init];
            vc.delegate = self;
            [self.navigationController pushViewController:vc animated:YES];
            [_backView4 removeFromSuperview];
            [_backView5 removeFromSuperview];
            [_backView6 removeFromSuperview];
            _backView7 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView3.frame)+10, kSCREEN_WIDTH, 40)];
            _backView7.backgroundColor = [UIColor whiteColor];
            [self.scrollView addSubview:_backView7];

            UIButton *addPartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
            [addPartBtn setTitle:@"增加配件" forState:UIControlStateNormal];
            [addPartBtn setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
            [addPartBtn addTarget:self action:@selector(addView) forControlEvents:UIControlEventTouchUpInside];
            [_backView7 addSubview:addPartBtn];
            [addPartBtn mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerX.equalTo(_backView7);
                make.top.equalTo(_backView7).offset(5);
                make.size.mas_equalTo(CGSizeMake(80, 30));
            }];
            UIImageView *addImage = [[UIImageView alloc]init];
            addImage.image = [UIImage imageNamed:@"add_b"];
            [_backView7 addSubview:addImage];
            [addImage mas_makeConstraints:^(MASConstraintMaker *make) {
                make.centerY.equalTo(_backView7);
                make.right.equalTo(addPartBtn.mas_left).offset(0);
                make.size.mas_equalTo(CGSizeMake(15, 15));
            }];
            _backView5 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView7.frame)+10, kSCREEN_WIDTH, 200)];
            _backView5.backgroundColor = [UIColor whiteColor];
            [self.scrollView addSubview:_backView5];
            
            //图片上传
            UILabel *photoUp = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 60, 21)];
            photoUp.adjustsFontSizeToFitWidth = YES;
            photoUp.text = @"图片上传";
            photoUp.textColor = UIColorFromRGB(0x4d4d4d);
            photoUp.font = [UIFont systemFontOfSize:15.0];
            [_backView5 addSubview:photoUp];
            
            UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
            layout.itemSize = CGSizeMake(imageSize, imageSize);
            layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
            layout.minimumLineSpacing = 10;
            UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(80, 0, self.view.frame.size.width-90, imageSize + 20) collectionViewLayout:layout];
            self.collectionView = collectionView;
            [self.collectionView registerClass:[KKUploadPhotoCollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellId];
            self.collectionView.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
            self.collectionView.delegate = self;
            self.collectionView.dataSource = self;
            self.collectionView.backgroundColor = [UIColor whiteColor];
            [_backView5 addSubview:collectionView];
            //备注信息
            UILabel *BZmassage = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(collectionView.frame)+5, 60, 21)];
            BZmassage.adjustsFontSizeToFitWidth = YES;
            BZmassage.text = @"备注信息";
            BZmassage.textColor = UIColorFromRGB(0x4d4d4d);
            BZmassage.font = [UIFont systemFontOfSize:15.0];
            [_backView5 addSubview:BZmassage];
            
            _bztextView = [[PHATextView alloc]initWithFrame:CGRectMake(90, CGRectGetMaxY(collectionView.frame)+5,kSCREEN_WIDTH/4*3-10, 80)];
            _bztextView.font = [UIFont systemFontOfSize:13.0];
            _bztextView.backgroundColor = UIColorFromRGB(0xf0f0f0);
            _bztextView.placeholder = @"不超过100个字符";
            _bztextView.returnKeyType = UIReturnKeyDone;
            _bztextView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
            _bztextView.layer.borderWidth = 0.5;
            _bztextView.layer.cornerRadius = 3;
            [_backView5 addSubview:_bztextView];
            
            _backView6 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView5.frame)+10, kSCREEN_WIDTH, 60)];
            _backView6.backgroundColor = [UIColor whiteColor];
            [self.scrollView addSubview:_backView6];
            
            //提交取消bttuon
            _updata = [UIButton buttonWithType:UIButtonTypeSystem];
            [_updata setTitle:@"提交" forState:UIControlStateNormal];
            [_updata setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            _updata.backgroundColor = UIColorFromRGB(0x2dd500);
            [_updata addTarget:self action:@selector(up) forControlEvents:UIControlEventTouchUpInside];
            [_backView6 addSubview:_updata];
            [_updata mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_backView6).offset(10);
                make.left.equalTo(self.scrollView).offset((kSCREEN_WIDTH/3-20)/2);
                make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
            }];
            
            UIButton *cancerl = [UIButton buttonWithType:UIButtonTypeSystem];
            [cancerl setTitle:@"取消" forState:UIControlStateNormal];
            [cancerl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
            [cancerl addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
            cancerl.backgroundColor = UIColorFromRGB(0xd50037);
            [_backView6 addSubview:cancerl];
            [cancerl mas_makeConstraints:^(MASConstraintMaker *make) {
                make.top.equalTo(_backView6).offset(10);
                make.left.equalTo(_updata.mas_right).offset(20);
                make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
            }];
            self.scrollView.contentSize = CGSizeMake(kSCREEN_WIDTH, CGRectGetMaxY(_backView6.frame)+50);

        }
        [self.tableview reloadData];

       
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"%@",error);
    }];
    
    }
}
//创建tableview
- (void)inittableview{

    [_backView4 removeFromSuperview];
    [_backView5 removeFromSuperview];
    [_backView6 removeFromSuperview];
    if (stat == 1) {
        

        self.tableview.dataSource = self;
        self.tableview.delegate = self;
        [self.scrollView addSubview:self.tableview];
        
        _backView5 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableview.frame)+10, kSCREEN_WIDTH, 200)];
        _backView5.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_backView5];
        
        //图片上传
        UILabel *photoUp = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 60, 21)];
        photoUp.adjustsFontSizeToFitWidth = YES;
        photoUp.text = @"图片上传";
        photoUp.textColor = UIColorFromRGB(0x4d4d4d);
        photoUp.font = [UIFont systemFontOfSize:15.0];
        [_backView5 addSubview:photoUp];
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(imageSize, imageSize);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 10;
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(80, 0, self.view.frame.size.width-90, imageSize + 20) collectionViewLayout:layout];
        self.collectionView = collectionView;
        [self.collectionView registerClass:[KKUploadPhotoCollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellId];
        self.collectionView.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        self.collectionView.backgroundColor = [UIColor whiteColor];
        [_backView5 addSubview:collectionView];
        //备注信息
        UILabel *BZmassage = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(collectionView.frame)+5, 60, 21)];
        BZmassage.adjustsFontSizeToFitWidth = YES;
        BZmassage.text = @"备注信息";
        BZmassage.textColor = UIColorFromRGB(0x4d4d4d);
        BZmassage.font = [UIFont systemFontOfSize:15.0];
        [_backView5 addSubview:BZmassage];
        
        _bztextView = [[PHATextView alloc]initWithFrame:CGRectMake(90, CGRectGetMaxY(collectionView.frame)+5,kSCREEN_WIDTH/4*3-10, 80)];
        _bztextView.font = [UIFont systemFontOfSize:13.0];
        _bztextView.backgroundColor = UIColorFromRGB(0xf0f0f0);
        _bztextView.placeholder = @"不超过100个字符";
        _bztextView.returnKeyType = UIReturnKeyDone;
        //_bztextView.textColor = UIColorFromRGB(0x4d4d4d);
        _bztextView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        _bztextView.layer.borderWidth = 0.5;
        _bztextView.layer.cornerRadius = 3;
        [_backView5 addSubview:_bztextView];
        
        _backView6 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView5.frame)+10, kSCREEN_WIDTH, 60)];
        _backView6.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_backView6];
        
        //提交取消bttuon
        _updata = [UIButton buttonWithType:UIButtonTypeSystem];
        [_updata setTitle:@"提交" forState:UIControlStateNormal];
        [_updata setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _updata.backgroundColor = UIColorFromRGB(0x2dd500);
        [_updata addTarget:self action:@selector(up) forControlEvents:UIControlEventTouchUpInside];
        [_backView6 addSubview:_updata];
        [_updata mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_backView6).offset(10);
            make.left.equalTo(self.scrollView).offset((kSCREEN_WIDTH/3-20)/2);
            make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
        }];
        
        UIButton *cancerl = [UIButton buttonWithType:UIButtonTypeSystem];
        [cancerl setTitle:@"取消" forState:UIControlStateNormal];
        [cancerl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancerl addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        cancerl.backgroundColor = UIColorFromRGB(0xd50037);
        [_backView6 addSubview:cancerl];
        [cancerl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_backView6).offset(10);
            make.left.equalTo(_updata.mas_right).offset(20);
            make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
        }];
        self.scrollView.contentSize = CGSizeMake(kSCREEN_WIDTH, CGRectGetMaxY(_backView6.frame)+50);
    }else{
        
        
        [_backView7 removeFromSuperview];
        //重新绘制tableview的高度
        CGRect rect = self.tableview.frame;
        rect.size.height = 120*_alldata.count;
        self.tableview.frame = rect;
        self.tableview.dataSource = self;
        self.tableview.delegate = self;
        [self.scrollView addSubview:self.tableview];

        _backView7 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(self.tableview.frame)+1, kSCREEN_WIDTH, 40)];
        _backView7.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_backView7];

        UIButton *addPartBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        [addPartBtn setTitle:@"增加配件" forState:UIControlStateNormal];
        [addPartBtn setTitleColor:UIColorFromRGB(0x4d4d4d) forState:UIControlStateNormal];
        [addPartBtn addTarget:self action:@selector(addView) forControlEvents:UIControlEventTouchUpInside];
        [_backView7 addSubview:addPartBtn];
        [addPartBtn mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerX.equalTo(_backView7);
            make.top.equalTo(_backView7).offset(5);
            make.size.mas_equalTo(CGSizeMake(80, 30));
        }];
        UIImageView *addImage = [[UIImageView alloc]init];
        addImage.image = [UIImage imageNamed:@"add_b"];
        [_backView7 addSubview:addImage];
        [addImage mas_makeConstraints:^(MASConstraintMaker *make) {
            make.centerY.equalTo(_backView7);
            make.right.equalTo(addPartBtn.mas_left).offset(0);
            make.size.mas_equalTo(CGSizeMake(15, 15));
        }];
        _backView5 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView7.frame)+1, kSCREEN_WIDTH, 200)];
        _backView5.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_backView5];
        
        //图片上传
        UILabel *photoUp = [[UILabel alloc]initWithFrame:CGRectMake(10, 10, 60, 21)];
        photoUp.adjustsFontSizeToFitWidth = YES;
        photoUp.text = @"图片上传";
        photoUp.textColor = UIColorFromRGB(0x4d4d4d);
        photoUp.font = [UIFont systemFontOfSize:15.0];
        [_backView5 addSubview:photoUp];
        
        UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
        layout.itemSize = CGSizeMake(imageSize, imageSize);
        layout.scrollDirection = UICollectionViewScrollDirectionHorizontal;
        layout.minimumLineSpacing = 10;
        UICollectionView *collectionView = [[UICollectionView alloc]initWithFrame:CGRectMake(80, 0, self.view.frame.size.width-90, imageSize + 20) collectionViewLayout:layout];
        self.collectionView = collectionView;
        [self.collectionView registerClass:[KKUploadPhotoCollectionViewCell class] forCellWithReuseIdentifier:collectionViewCellId];
        self.collectionView.contentInset = UIEdgeInsetsMake(0, 10, 0, 10);
        self.collectionView.delegate = self;
        self.collectionView.dataSource = self;
        self.collectionView.backgroundColor = [UIColor whiteColor];
        [_backView5 addSubview:collectionView];
        //备注信息
        UILabel *BZmassage = [[UILabel alloc]initWithFrame:CGRectMake(10, CGRectGetMaxY(collectionView.frame)+5, 60, 21)];
        BZmassage.adjustsFontSizeToFitWidth = YES;
        BZmassage.text = @"备注信息";
        BZmassage.textColor = UIColorFromRGB(0x4d4d4d);
        BZmassage.font = [UIFont systemFontOfSize:15.0];
        [_backView5 addSubview:BZmassage];
        
        _bztextView = [[PHATextView alloc]initWithFrame:CGRectMake(90, CGRectGetMaxY(collectionView.frame)+5,kSCREEN_WIDTH/4*3-10, 80)];
        _bztextView.font = [UIFont systemFontOfSize:13.0];
        _bztextView.backgroundColor = UIColorFromRGB(0xf0f0f0);
        _bztextView.placeholder = @"不超过100个字符";
        _bztextView.returnKeyType = UIReturnKeyDone;
        //_bztextView.textColor = UIColorFromRGB(0x4d4d4d);
        _bztextView.layer.borderColor = [[UIColor lightGrayColor] CGColor];
        _bztextView.layer.borderWidth = 0.5;
        _bztextView.layer.cornerRadius = 3;
        [_backView5 addSubview:_bztextView];
        
        _backView6 = [[UIView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView5.frame)+10, kSCREEN_WIDTH, 60)];
        _backView6.backgroundColor = [UIColor whiteColor];
        [self.scrollView addSubview:_backView6];
        
        //提交取消bttuon
        _updata = [UIButton buttonWithType:UIButtonTypeSystem];
        [_updata setTitle:@"提交" forState:UIControlStateNormal];
        [_updata setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        _updata.backgroundColor = UIColorFromRGB(0x2dd500);
        [_updata addTarget:self action:@selector(up) forControlEvents:UIControlEventTouchUpInside];
        [_backView6 addSubview:_updata];
        [_updata mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_backView6).offset(10);
            make.left.equalTo(self.scrollView).offset((kSCREEN_WIDTH/3-20)/2);
            make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
        }];
        
        UIButton *cancerl = [UIButton buttonWithType:UIButtonTypeSystem];
        [cancerl setTitle:@"取消" forState:UIControlStateNormal];
        [cancerl setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
        [cancerl addTarget:self action:@selector(back) forControlEvents:UIControlEventTouchUpInside];
        cancerl.backgroundColor = UIColorFromRGB(0xd50037);
        [_backView6 addSubview:cancerl];
        [cancerl mas_makeConstraints:^(MASConstraintMaker *make) {
            make.top.equalTo(_backView6).offset(10);
            make.left.equalTo(_updata.mas_right).offset(20);
            make.size.mas_equalTo(CGSizeMake(kSCREEN_WIDTH/3, 40));
        }];
        self.scrollView.contentSize = CGSizeMake(kSCREEN_WIDTH, CGRectGetMaxY(_backView6.frame)+50);
        
        [self.tableview reloadData];

    }
    
}

- (void)notice:(NSNotification *)notification{

    //_alldata = [[NSMutableArray alloc]init];
    NSDictionary *dic = notification.userInfo;
    ExpenseModel *model = [[ExpenseModel alloc]init];
    model.djnum = _Number.text;
    model.aliph = @"1";
    model.PJbianhao = dic[@"num"];
    model.value = [dic[@"value"]integerValue];
    model.discrib = dic[@"disc"];
    model.unit = dic[@"unit"];
    [_alldata addObject:model];
    [self inittableview];
    [[NSNotificationCenter defaultCenter]removeObserver:@"cellnotice1"];

}

#pragma mark-->tableview
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _alldata.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
          return 120.0;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ExpenseCell *cell = [[ExpenseCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:@"cell"];
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    cell.delegate = self;
    ExpenseModel *model = _alldata[indexPath.row];
    [cell fillCellWithModel:model Index:indexPath.row];
    return cell;
}
#pragma mark-->删除代理
- (void)Refresh:(NSInteger)index
{
    
    UIAlertController *alert=[UIAlertController alertControllerWithTitle:[NSString stringWithFormat:@"你确定要删除配件%ld吗",index+1] message:nil preferredStyle:UIAlertControllerStyleAlert];
    
    
    UIAlertAction *ok=[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        
        [_alldata removeObjectAtIndex:index];
        
        stat = 0;
        [self inittableview];


    }];
    UIAlertAction *no=[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
        
    }];
    
    [alert addAction:ok];
    [alert addAction:no];
    
    [self presentViewController:alert animated:YES completion:nil];

}
//增加配件btn点击事件
- (void)addView{
    
    PartChooseVC *vc = [[PartChooseVC alloc]init];
    vc.delegate = self;
    [self.navigationController pushViewController:vc animated:YES];
    
}
- (void)updataDt{
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.Popview animated:YES];
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:K_GZtype parameters:nil progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        TypeDataModel *model = [[TypeDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (SectionOneFaultModel *OneModel in model.FaultType) {
            
            [_dataSource0 addObject:OneModel];
            [_typeIDArr1 addObject:[NSString stringWithFormat:@"%ld",OneModel.ID]];
            //第二层数组模型 2层
            NSMutableArray *arr1 = [[NSMutableArray alloc]init];
            //第二层数组 ID 2层
            NSMutableArray *IDArr1 = [[NSMutableArray alloc]init];
            //第三层数组ID   3层
            NSMutableArray *IDArr3 = [[NSMutableArray alloc]init];
            //第三层数组模型  3层
            NSMutableArray *arr3 = [[NSMutableArray alloc]init];
            for (SectionTowFaultModel *TowModel in OneModel.faultTypes) {
                [arr1 addObject:TowModel];
                [IDArr1 addObject:[NSString stringWithFormat:@"%ld",TowModel.ID]];
                NSMutableArray *arr2 = [[NSMutableArray alloc]init];
                NSMutableArray *IDArr2 = [[NSMutableArray alloc]init];
                for (SectionThreeFaultModel *ThreeModel in TowModel.faultTypes) {
                    [arr2 addObject:ThreeModel];
                    [IDArr2 addObject:[NSString stringWithFormat:@"%ld",ThreeModel.ID]];
                }
                [IDArr3 addObject:IDArr2];
                [arr3 addObject:arr2];
            }
            [_typeIDArr2 addObject:IDArr1];
            [_dataSource1 addObject:arr1];
            [_typeIDArr3 addObject:IDArr3];
            [_dataSource2 addObject:arr3];
            
        }

        [self initView];
        
        [MBProgressHUD hideHUDForView:self.Popview animated:YES];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        [MBProgressHUD hideHUDForView:self.Popview animated:YES];
    }];


}
- (void)initPopView{
    
    
    self.Popview = [[PopupView alloc]initWithBounds:CGRectMake(0, 15, kSCREEN_WIDTH, kSCREEN_HEIGHT-15) titleMenus:_data];
    self.Popview.parentVC = self;
    self.Popview.delegate = self;
    LewPopupViewAnimationSlide *animation = [[LewPopupViewAnimationSlide alloc]init];
    
    animation.type = LewPopupViewAnimationSlideTypeBottomBottom;
    [self lew_presentPopupView:self.Popview animation:animation dismissed:^{
        NSLog(@"动画结束");
    }];
}

- (void)initView{

    _MenusView = [[ChooseMenus alloc]initWithFrame:CGRectMake(0, self.view.frame.size.height/3*2, self.view.frame.size.width, self.view.frame.size.height/3)];
    _MenusView.backgroundColor = [UIColor whiteColor];
    _MenusView.dataSource = self;
    
    [_MenusView typeIDOne:_typeIDArr1];
    [_MenusView typeIDTow:_typeIDArr2];
    [_MenusView typeIDThree:_typeIDArr3];
    [self.Popview addSubview:_MenusView];
    
    [_MenusView TitleBlock:^(NSString *block , NSInteger ID) {

        [_Popview.btn setTitle:block forState:UIControlStateNormal];
        faultType = ID;
    }];

}
- (void)chooseType:(UIButton *)sender{
    
    if (isSelect) {
        //isSelect = NO;btn再次点击移除选择菜单
        isSelect = !isSelect;
        [_dataSource0 removeAllObjects];
        [_dataSource1 removeAllObjects];
        [_dataSource2 removeAllObjects];
        [_typeIDArr1 removeAllObjects];
        [_typeIDArr2 removeAllObjects];
        [_typeIDArr3 removeAllObjects];
        [_MenusView removeFromSuperview];
    }else{
        [self updataDt];
        isSelect = YES;
    }
    
}
- (void)choosePson:(UIButton *)sender{
    
    MHActionSheet *actionSheet = [[MHActionSheet alloc] initSheetWithTitle:nil style:MHSheetStyleDefault itemTitles:_UpPsonNameArr];
    __weak typeof(self) weakSelf = self;
    [actionSheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
        
        [weakSelf.Popview.BSpsonBtn setTitle:title forState:UIControlStateNormal];
        [weakSelf.Popview.BSpsonBtn setTitleColor:UIColorFromRGB(0xb6b6b6) forState:UIControlStateNormal];
        UpPsonid = [weakSelf.UpPsonId[index]integerValue];
    }];
}
- (void)CancelChooseView:(UIButton *)sender{
    
    isSelect = !isSelect;
    [_dataSource0 removeAllObjects];
    [_dataSource1 removeAllObjects];
    [_dataSource2 removeAllObjects];
    [_typeIDArr1 removeAllObjects];
    [_typeIDArr2 removeAllObjects];
    [_typeIDArr3 removeAllObjects];
    [_MenusView removeFromSuperview];
}

#pragma mark - WSDropMenuView DataSource -
- (NSInteger)dropMenuView:(ChooseMenus *)dropMenuView numberWithIndexPath:(WSIndexPath *)indexPath{
    
    //WSIndexPath 类里面有注释
    
    if (indexPath.row == WSNoFound) {
        
        return _dataSource0.count;
    }
    if (indexPath.row != WSNoFound && indexPath.item == WSNoFound) {
        NSArray *arr = _dataSource1[indexPath.row];
        return arr.count;
    }
    
    if (indexPath.row != WSNoFound && indexPath.item != WSNoFound && indexPath.rank == WSNoFound) {
        NSArray *arr = _dataSource2[indexPath.row][indexPath.item];
        return arr.count;
    }
    

    return 0;
}

- (NSString *)dropMenuView:(ChooseMenus *)dropMenuView titleWithIndexPath:(WSIndexPath *)indexPath{
    
    //return [NSString stringWithFormat:@"%ld",indexPath.row];
    
    //左边 第一级
    if (indexPath.row != WSNoFound && indexPath.item == WSNoFound) {
        SectionOneFaultModel *model = _dataSource0[indexPath.row];
        
        return model.name;
    }
    
    if (indexPath.row != WSNoFound && indexPath.item != WSNoFound && indexPath.rank == WSNoFound) {
        
        SectionTowFaultModel *model = _dataSource1[indexPath.row][indexPath.item];
        
        
        
        return model.name;
    }
    
    if (indexPath.row != WSNoFound && indexPath.item != WSNoFound && indexPath.rank != WSNoFound) {
        SectionThreeFaultModel *model = _dataSource2[indexPath.row][indexPath.item][indexPath.rank];
        
        return model.name;
    }

    
    return @"";
    
}
- (void)chooseTime:(UIButton *)sender{
    btnTag = sender.tag;
    FDAlertView *alert = [[FDAlertView alloc] init];
    
    RBCustomDatePickerView * contentView=[[RBCustomDatePickerView alloc]init];
    contentView.delegate=self;
    contentView.frame = CGRectMake(0, 0, 320, 300);
    alert.contentView = contentView;
    [alert show];
}
-(void)getTimeToValue:(NSString *)theTimeStr
{
    if (btnTag == 2001) {
        [_startTime setTitle:theTimeStr forState:UIControlStateNormal];
    }else {
        [_endTime setTitle:theTimeStr forState:UIControlStateNormal];
    }
    //NSLog(@"我获取到时间了，时间是===%@",theTimeStr);
}
- (void)ChooseSB:(UIButton *)sender
{
    MHActionSheet *actionSheet = [[MHActionSheet alloc] initSheetWithTitle:nil style:MHSheetStyleDefault itemTitles:self.SBArry];
    __weak typeof(self) weakSelf = self;
    [actionSheet didFinishSelectIndex:^(NSInteger index, NSString *title) {
        
        weakSelf.Popview.SbChooseLab.text = title;
        sbid = [weakSelf.eqidArray[index]integerValue];
    }];
}
//根据站点ID获取设备
- (void)SBnetworking{
    
    self.manager.responseSerializer = [AFHTTPResponseSerializer serializer];
    [_manager POST:EquipURL parameters:@{@"stationId":[NSString stringWithFormat:@"%ld",self.stationid]} progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        [self.SBArry removeAllObjects];
        [self.eqidArray removeAllObjects];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        XJEqDataModel *dataModel = [[XJEqDataModel alloc]initWithDictionary:dic[@"data"] error:nil];
        for (XJEqListModel *model in dataModel.Equiplist) {
            [_SBArry addObject:model.equipName];
            [_eqidArray addObject:[NSString stringWithFormat:@"%ld",model.equipId]];
        }

    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        
    }];
}

- (void)refreshLocation:(UIButton *)sender{
    
    [_LocationManager startUpdatingLocation];
}
//上传
- (void)up{
    
    [UIView animateWithDuration:0 delay:1.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
        _updata.userInteractionEnabled = NO;
    } completion:^(BOOL finished) {
        _updata.userInteractionEnabled = YES;
    }];
//故障详情点击了 close按键的话
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *title = [user objectForKey:@"title"];
    if (title.length <1) {
        UpPsonid = 0;
        sbid = 0;
        faultType = 0;
    }
    if (_bztextView.text.length > 100) {
        [self showAlert:@"备注内容超过限定长度" message:nil actionWithTitle:@"确定"];
    }else if(_bztextView.text.length < 1 || [_startTime.titleLabel.text isEqualToString:@"选择时间"] || [_endTime.titleLabel.text isEqualToString:@"选择时间"]){
        [self showAlert:@"温馨提示" message:@"请完善提交信息" actionWithTitle:@"确定"];
    }
    else if ((lat == 0 && lnt == 0) || _place.length < 1){
        
        [self showAlert:@"温馨提示" message:@"获取不到您的位置信息,请重新定位" actionWithTitle:@"确定"];
        
    }else if (state == 1 && faultType == 0 && sbid == 0){
        [self showAlert:@"温馨提示" message:@"请填写故障上报详情再提交" actionWithTitle:@"确定"];
    }
    else{
        
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    self.manager.requestSerializer = [AFHTTPRequestSerializer serializer];
    //读取userdefault数据
    NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
    NSString *bzDis = _bztextView.text;
    NSString *fDis = [user objectForKey:@"discrib"];//故障描述
    NSString *title = [user objectForKey:@"title"];
        //NSLog(@"%ld,%ld,%ld",stat,equipState,state);
        if ((stat == 2 && equipState == 1 && _Number.text.length < 1 ) || (stat == 2 && equipState == 2 && state == 0 && _Number.text.length < 1)) {
            _paramete = @{stationID:[NSString stringWithFormat:@"%ld",self.stationid],@"startTime":_startTime.titleLabel.text,@"endTime":_endTime.titleLabel.text,ycstate:[NSString stringWithFormat:@"%ld",equipState],sbState:[NSString stringWithFormat:@"%ld",state],userid:[NSString stringWithFormat:@"%ld",self.userId],xjDisc:bzDis,@"sendTime":_time,@"lat":[NSString stringWithFormat:@"%f",lat],@"lnt":[NSString stringWithFormat:@"%f",lnt],@"address":_place};
        }else if ((stat == 2 && equipState == 1 && _Number.text.length>1) || (stat == 2 && equipState == 2 && state == 0 && _Number.text.length>1)){
            _listarr = [[NSMutableArray alloc]init];
            for (NSInteger i = 0; i < _alldata.count; ++i) {
                ExpenseModel *model = _alldata[i];
                NSDictionary *dic = @{Code:model.PJbianhao,Values:[NSString stringWithFormat:@"%ld",model.value]};
                [_listarr addObject:dic];
            }
            _paramete = @{stationID:[NSString stringWithFormat:@"%ld",self.stationid],@"startTime":_startTime.titleLabel.text,@"endTime":_endTime.titleLabel.text,ycstate:[NSString stringWithFormat:@"%ld",equipState],sbState:[NSString stringWithFormat:@"%ld",state],userid:[NSString stringWithFormat:@"%ld",self.userId],xjDisc:bzDis,PartNum:_Number.text,PartList:_listarr,@"sendTime":_time,@"lat":[NSString stringWithFormat:@"%f",lat],@"lnt":[NSString stringWithFormat:@"%f",lnt],@"address":_place};
            
        } else if (stat == 2 && equipState == 2 && state == 1 && _Number.text.length < 1){

            _paramete = @{stationID:[NSString stringWithFormat:@"%ld",self.stationid],@"startTime":_startTime.titleLabel.text,@"endTime":_endTime.titleLabel.text,ycstate:[NSString stringWithFormat:@"%ld",equipState],sbState:[NSString stringWithFormat:@"%ld",state],userid:[NSString stringWithFormat:@"%ld",self.userId],xjDisc:bzDis,equipid:[NSString stringWithFormat:@"%ld",sbid],FaultTime:_time,ftypeid:[NSString stringWithFormat:@"%ld",faultType],fTitle:title,fDiscrib:fDis,@"sendTime":_time,@"lat":[NSString stringWithFormat:@"%f",lat],@"lnt":[NSString stringWithFormat:@"%f",lnt],@"address":_place,@"HeadPsonId":[NSString stringWithFormat:@"%ld",UpPsonid]};

        }else if (stat == 2 && equipState == 2 && state == 1 && _Number.text.length>1){
            _listarr = [[NSMutableArray alloc]init];
            for (NSInteger i = 0; i < _alldata.count; ++i) {
                ExpenseModel *model = _alldata[i];
                NSDictionary *dic = @{Code:model.PJbianhao,Values:[NSString stringWithFormat:@"%ld",model.value]};
                [_listarr addObject:dic];
            }
            _paramete = @{stationID:[NSString stringWithFormat:@"%ld",self.stationid],@"startTime":_startTime.titleLabel.text,@"endTime":_endTime.titleLabel.text,ycstate:[NSString stringWithFormat:@"%ld",equipState],sbState:[NSString stringWithFormat:@"%ld",state],userid:[NSString stringWithFormat:@"%ld",self.userId],xjDisc:bzDis,equipid:[NSString stringWithFormat:@"%ld",sbid],FaultTime:_time,ftypeid:[NSString stringWithFormat:@"%ld",faultType],fTitle:title,fDiscrib:fDis,PartNum:_Number.text,PartList:_listarr,@"sendTime":_time,@"lat":[NSString stringWithFormat:@"%f",lat],@"lnt":[NSString stringWithFormat:@"%f",lnt],@"address":_place,@"HeadPsonId":[NSString stringWithFormat:@"%ld",UpPsonid]};

        }else if ((stat == 1 && equipState == 1) || (stat == 1 && equipState == 2 && state == 0)){
            _listarr = [[NSMutableArray alloc]init];
            for (NSInteger i = 0; i < _alldata.count; ++i) {
                ExpenseModel *model = _alldata[i];
                NSDictionary *dic = @{Code:model.PJbianhao,Values:[NSString stringWithFormat:@"%ld",model.value]};
                [_listarr addObject:dic];
            }
            _paramete = @{stationID:[NSString stringWithFormat:@"%ld",self.stationid],@"startTime":_startTime.titleLabel.text,@"endTime":_endTime.titleLabel.text,ycstate:[NSString stringWithFormat:@"%ld",equipState],sbState:[NSString stringWithFormat:@"%ld",state],userid:[NSString stringWithFormat:@"%ld",self.userId],xjDisc:bzDis,PartNum:_Number.text,PartList:_listarr,@"sendTime":_time,@"lat":[NSString stringWithFormat:@"%f",lat],@"lnt":[NSString stringWithFormat:@"%f",lnt],@"address":_place};

        }else if (stat == 1 && equipState == 2 && state == 1){
            _listarr = [[NSMutableArray alloc]init];
            for (NSInteger i = 0; i < _alldata.count; ++i) {
                ExpenseModel *model = _alldata[i];
                NSDictionary *dic = @{Code:model.PJbianhao,Values:[NSString stringWithFormat:@"%ld",model.value]};
                [_listarr addObject:dic];
            }
            _paramete = @{stationID:[NSString stringWithFormat:@"%ld",self.stationid],@"startTime":_startTime.titleLabel.text,@"endTime":_endTime.titleLabel.text,ycstate:[NSString stringWithFormat:@"%ld",equipState],sbState:[NSString stringWithFormat:@"%ld",state],userid:[NSString stringWithFormat:@"%ld",self.userId],xjDisc:bzDis,equipid:[NSString stringWithFormat:@"%ld",sbid],FaultTime:_time,ftypeid:[NSString stringWithFormat:@"%ld",faultType],fTitle:title,fDiscrib:fDis,PartNum:_Number.text,PartList:_listarr,@"sendTime":_time,@"lat":[NSString stringWithFormat:@"%f",lat],@"lnt":[NSString stringWithFormat:@"%f",lnt],@"address":_place,@"HeadPsonId":[NSString stringWithFormat:@"%ld",UpPsonid]};
        }

        NSSLog(@"%@",_paramete);
    [_manager POST:K_XJLR parameters:_paramete constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        
        for (int i = 0; i<self.imageArray.count; i++) {
            
            NSData *imageData =UIImageJPEGRepresentation(self.imageArray[i], 0.5);
            CGFloat dataBytes = imageData.length/1000.0;
            CGFloat maxQuality = 0.5f;
            CGFloat lastData = dataBytes;
            while (dataBytes > 300 && maxQuality > 0.1f) {
                maxQuality = maxQuality - 0.1f;
                imageData = UIImageJPEGRepresentation(self.imageArray[i], maxQuality);
                dataBytes = imageData.length / 1000.0;
                if (lastData == dataBytes) {
                    break;
                }else{
                    lastData = dataBytes;
                }  
            }
            //NSLog(@"%f",dataBytes);
            //if (dataBytes<300 || dataBytes == 300) {
                
                NSString *fileName = [NSString  stringWithFormat:@"image%d.jpg", i];
                [formData appendPartWithFileData:imageData name:@"GZLR" fileName:fileName mimeType:@"image/jpeg"];
           // }


            
        }

        
    } progress:^(NSProgress * _Nonnull uploadProgress) {
        
    } success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
    [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingMutableContainers error:nil];
        NSLog(@"%@",dic);
        NSInteger status = [dic[@"status"]integerValue];
        NSLog(@"%ld",status);
        if (status == 1) {
            //延时操作
            [UIView animateWithDuration:0 delay:2.0 options:UIViewAnimationOptionAllowUserInteraction animations:^{
                
                [[YXAlertHUD stateHUDWithHUDTyep:0 message:@"提交成功" textColor:[UIColor blackColor] iconColor:[UIColor greenColor]] show];
                
            } completion:^(BOOL finished) {
                
                [self.navigationController popViewControllerAnimated:YES];
            }];
            
        }else{
            [self showAlert:@"提交失败" message:dic[@"message"] actionWithTitle:@"我知道了"];
        }
        
        
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
       
        [MBProgressHUD hideHUDForView:self.view animated:YES];
        NSHTTPURLResponse * responses = (NSHTTPURLResponse *)task.response;
        NSInteger status = responses.statusCode;
        //        NSSLog(@"%ld",(long)responses.statusCode);
        if (status >=500) {
            [self showAlert:@"提交失败" message:@"服务器出错" actionWithTitle:@"我知道了"];
        }else{
            [self showAlert:@"提交失败" message:[error userInfo][@"NSLocalizedDescription"] actionWithTitle:@"我知道了"];
        }
    }];
    }
}
#pragma mark 封装提示框
- (void)showAlert:(NSString *)Title message:(NSString *)message actionWithTitle:(NSString *)actionWithTitle{
    UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:Title message:message preferredStyle:UIAlertControllerStyleAlert];
    [alertVC addAction:[UIAlertAction actionWithTitle:actionWithTitle style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        
    }]];
    [self presentViewController:alertVC animated:YES completion:nil];
}

- (void)back{

    [self.navigationController popViewControllerAnimated:YES];
}

- (UITableView *)tableview {
    
    if (!_tableview) {
        
        _tableview = [[UITableView alloc]initWithFrame:CGRectMake(0, CGRectGetMaxY(_backView3.frame)+1, kSCREEN_WIDTH, 120*_alldata.count) style:UITableViewStylePlain];
    }
    return _tableview;
}

@end
